<?php

session_start();
defined('BASE_PATH') || define('BASE_PATH', realpath(dirname(__FILE__)));
include_once ("config/config.php");
include_once ("config/common.php");
error_reporting(1);
//print_r($_SESSION);die;
$cookie_life = time() + 31536000; //1 year
switch ($_REQUEST['action']) {
    case 'tracuutuoilamnha':
        
        include $_SERVER ['DOCUMENT_ROOT']."/ext/nusoap-0.9.5/lib/nusoap.php";
        $client = new nusoap_client('http://www.vanmenh.com/lamnha.asmx?WSDL', true);
        $client->soap_defencoding = 'UTF-8';
        $client->decode_utf8 = false;
        $arrPost = array();
        $arrPost['MaHienThi'] = 'HRC_HTML';
        $arrPost['LaNamGioi'] = '1';
        $temNgaySinh = explode('/', $_POST['ngaysinh']);
        $arrPost['NgayThangNamSinhDuongLich'] = trim(intval($temNgaySinh[1]).'/'.intval($temNgaySinh[0]).'/'.intval($temNgaySinh[2]));
        $arrPost['NamXayNha'] = intval($_POST['namxaynha']);
        
        $action = 'TuoiLamNha';
        $condition = "gioitinh=".$arrPost['LaNamGioi'];
        if(strlen(intval($temNgaySinh[0]))==1){
            $likeMonth = '0'.intval($temNgaySinh[0]);
        }
        if(strlen(intval($temNgaySinh[1]))==1){
            $likeDay = '0'.intval($temNgaySinh[1]);
        }
        $condition = $condition . " AND ngaysinh LIKE '".$temNgaySinh[2].'-'.$likeMonth.'-'.$likeDay."'";
        $condition = $condition . " AND namxaynha=".$arrPost['NamXayNha'];
        $condition = $condition . " AND action='$action'";
        $sql = "SELECT * FROM cache_soap WHERE 1 AND $condition";
        $rs = $db->query_first($sql);
        if($rs['id']){
            echo $rs['result'];
        }else{
            $resultSoap = $client->call('TuoiLamNha',$arrPost);
            if($resultSoap['TuoiLamNhaResult']){
                $gioitinh = intval($arrPost['LaNamGioi']);
                $ngaysinh = trim(intval($temNgaySinh[2]).'-'.intval($temNgaySinh[1]).'-'.intval($temNgaySinh[0]));
                $namxaynha = intval($arrPost['NamXayNha']);
                $result = mysql_real_escape_string(trim($resultSoap['TuoiLamNhaResult']));
                
                $sqlInsert = "INSERT INTO cache_soap (gioitinh,ngaysinh,namxaynha,result,action) VALUES ($gioitinh,'$ngaysinh',$namxaynha,'$result','$action')";
                $db->query($sqlInsert);
            }
            echo $resultSoap['TuoiLamNhaResult'];
        }
        break;
    case 'comment':
        $aid = intval($_POST['aid']);
        $name = mysql_escape_string(trim($_POST['name']));
        $email = mysql_escape_string(trim($_POST['email']));
        $comment = mysql_real_escape_string(trim($_POST['comment']));
        $verify = strtolower($_POST['verify']);
        $create_date = date('Y-m-d H:i:s');

        if ($verify != strtolower($_SESSION['captcha_val'])) {
            echo 'captcha_error';
        } else {
            $addCategorySql = "INSERT INTO comment (aid,name,email,comment,create_date,status) VALUES($aid,'$name','$email','$comment','$create_date','no')";
            $db->query($addCategorySql);
            $sqlUpdate = "UPDATE article SET last_comment='$create_date' WHERE id=$aid";
            $db->query($sqlUpdate);
            unset($_SESSION['captcha_val']);
            echo 'ok';
        }
        break;
    case 'comment_project':
        $project_id = intval($_POST['project_id']);
        $name = mysql_escape_string(trim($_POST['name']));
        $email = mysql_escape_string(trim($_POST['email']));
        $comment = mysql_real_escape_string(trim($_POST['comment']));
        $verify = strtolower($_POST['verify']);
        $create_date = date('Y-m-d H:i:s');

        if ($verify != strtolower($_SESSION['captcha_val'])) {
            echo 'captcha_error';
        } else {
            $addCategorySql = "INSERT INTO comments (to_id,name,email,comment,date_send,status,type) VALUES($project_id,'$name','$email','$comment','$create_date','no','project')";
            $db_ancu->query($addCategorySql);
            unset($_SESSION['captcha_val']);
            echo 'ok';
        }
        break;
    case 'project_search':
        //echo $_POST['geo_id'];
        if(intval($_POST['geo_id'])>0) {
            echo '<option value="0">Quận / Huyện...</option>';
            $resultDistrict = get_geo_by_parent_id(intval($_POST['geo_id']));
          //  echo '<select>';
            while($rs=$db->fetch_array($resultDistrict)) {
                if(intval($_POST['geo_id'])==$rs['geo_id']){
                    echo '<option value="'.$rs['geo_id'].'" selected="selected" >'.$rs['geo_title'].'</option>';
                }else{
                    echo '<option value="'.$rs['geo_id'].'" >'.$rs['geo_title'].'</option>';
                }
            }
           // echo '</select>';
        }else{
            echo '<option value="0">Quận / Huyện...</option>';
        }
    case 'ptSendQuestion':
        $cat_id = intval($_POST['cat_id']);
        $fullname = mysql_escape_string(trim($_POST['fullname']));
        $email = mysql_escape_string(trim($_POST['email']));
        $verify = strtolower(trim($_POST['verify']));
        $question = str_replace('\n', '<br/>', (mysql_real_escape_string(trim($_POST['content']))));
        $create_date = date('Y-m-d H:i:s');
        if ($verify != strtolower($_SESSION['captcha_val'])) {
            echo 'captcha_error';
        } else {
            if ($cat_id) {
                $addCategorySql = "INSERT INTO question (cat_id,fullname,email,question,create_date,last_answer) VALUES($cat_id,'$fullname','$email','$question','$create_date','$create_date')";
                $db->query($addCategorySql);
                echo $db->mysql_insert_id();
            }
        }
        break;

    case 'ptSendAnswer':
        $qid = intval($_POST['qid']);
        $fullname = mysql_escape_string(trim($_POST['fullname']));
        $email = mysql_escape_string(trim($_POST['email']));
        $verify = strtolower(trim($_POST['verify']));
        $answer = str_replace('\n', '<br/>', (mysql_real_escape_string(trim($_POST['content']))));
        $create_date = date('Y-m-d H:i:s');
        if ($verify != strtolower($_SESSION['captcha_val'])) {
            echo 'captcha_error';
        } else {
            if ($qid) {
                $addCategorySql = "INSERT INTO answer (qid,fullname,email,answer,create_date) VALUES($qid,'$fullname','$email','$answer','$create_date')";
                $db->query($addCategorySql);
                $updateQuestion = "UPDATE question SET last_answer='$create_date' WHERE id=$qid";
                $db->query($updateQuestion);
                echo 'ok';
            }
        }
        break;
    case 'ptLoadMoreAnswer':
        $last_id = intval($_GET['last_id']);
        $sql = "SELECT * FROM answer WHERE 1 AND id > $last_id LIMIT 10";
        $rs = $db->query($sql);
        $html = '';
        if ($rs) {
            while ($row = mysql_fetch_array($rs)) {
                $html .= '<li lang="'.$row['id'].'">';
                $html .= '<img src="'.$config ['phongthuy_images'].'/avatar.gif" title="" alt="" class="avatar" />';
                $html .= '<div class="reply-ct">';
                $html .= '<h2><a href="#"><b>'.$row['fullname'].'</b></a> '.date('h:i:s d/m/Y',  strtotime($row['create_date'])).'</h2>';
                $html .= '<p>';
                $html .= $row['answer'];
                $html .= '</p>';
                $html .= '<span id="thumb_up'.$row['id'].'" class="bgvote" lang="'.$row['id'].'">';
                $html .= '<span id="thumb_up_score'.$row['id'].'">'.$row['thumb_up'].'</span> <a href="#"><img src="'.$config ['phongthuy_images'].'/i-up.gif" title="" alt="" /></a>';
                $html .= '</span>';
                $html .= '<span class="danhgia">Đánh giá: <img src="'.$config ['phongthuy_images'].'/star.gif" /></span>';
                $html .= '</div>';
                $html .= '</li>';
            }
        }

        echo $html;

        break;
    case 'thumbUpAnswer':
        $id = intval($_POST['id']);
        if (isset($_COOKIE['voteAnswer'])) {
            $arrVote = explode('-', $_COOKIE['voteAnswer']);
            if (in_array($id, $arrVote)) {
                echo 'voted';
            } else {
                $strId = $_COOKIE['voteAnswer'] . '-' . $id;
                setcookie('voteAnswer', $strId,$cookie_life);
                $sql = "UPDATE answer SET thumb_up=thumb_up+1 WHERE id=$id";
                $db->query($sql);

                $sql = "SELECT thumb_up FROM answer WHERE id=$id";
                $rs = $db->query_first($sql);
                echo $rs['thumb_up'];
            }
        } else {
            setcookie('voteAnswer', $id,$cookie_life);
            $sql = "UPDATE answer SET thumb_up=thumb_up+1 WHERE id=$id";
            $db->query($sql);

            $sql = "SELECT thumb_up FROM answer WHERE id=$id";
            $rs = $db->query_first($sql);
            echo $rs['thumb_up'];
        }
        break;
    case 'voteUp':
        $id = intval($_POST['id']);
        if (isset($_COOKIE['vote'])) {
            $arrVote = explode('-', $_COOKIE['vote']);
            if (in_array($id, $arrVote)) {
                echo 'voted';
            } else {
                $strId = $_COOKIE['vote'] . '-' . $id;
                setcookie('vote', $strId, $cookie_life);
                $sql = "UPDATE comment SET vote=vote+1, vote_up=vote_down+1 WHERE id=$id";
                $db->query($sql);

                $sql = "SELECT vote FROM comment WHERE status='yes' AND id=$id";
                $rs = $db->query_first($sql);
                echo $rs['vote'];
            }
        } else {
            setcookie('vote', $id, $cookie_life);
            $sql = "UPDATE comment SET vote=vote+1,vote_up=vote_up+1 WHERE id=$id";
            $db->query($sql);

            $sql = "SELECT vote FROM comment WHERE status='yes' AND id=$id";
            $rs = $db->query_first($sql);
            echo $rs['vote'];
        }
        break;
    case 'voteDown':
        $id = intval($_POST['id']);
        if (isset($_COOKIE['vote'])) {
            $arrVote = explode('-', $_COOKIE['vote']);
            if (in_array($id, $arrVote)) {
                echo 'voted';
            } else {
                $strId = $_COOKIE['vote'] . '-' . $id;
                setcookie('vote', $strId, $cookie_life);
                $sql = "UPDATE comment SET vote=vote-1, vote_down=vote_down+1 WHERE id=$id";
                $db->query($sql);

                $sql = "SELECT vote FROM comment WHERE status='yes' AND id=$id";
                $rs = $db->query_first($sql);
                echo $rs['vote'];
            }
        } else {
            setcookie('vote', $id, $cookie_life);
            $sql = "UPDATE comment SET vote=vote-1, vote_down=vote_down+1 WHERE id=$id";
            $db->query($sql);

            $sql = "SELECT vote FROM comment WHERE status='yes' AND id=$id";
            $rs = $db->query_first($sql);
            echo $rs['vote'];
        }


        break;
    case 'sendmail':
        include_once ("ext/phpmailer/class.phpmailer.php");
        include_once ("ext/phpmailer/class.smtp.php");

        $mail = new PHPMailer();

        $body = $_POST['email_content'];
        $body = eregi_replace("[\]", '', $body);


        $mail->CharSet = 'utf-8';
        $mail->IsSMTP();
        $mail->SMTPAuth = true;
        $mail->Host = "ssl://smtp.gmail.com"; // SMTP server
        $mail->Port = 465;                     // set the SMTP port for the GMAIL server
        $mail->Username = "nghiatruong812@gmail.com"; // SMTP account username
        $mail->Password = "nghia12345";        // SMTP account password
        /*         * ******************************************************************************** */

        $captcha = $_POST['captcha'];
        if (strtolower($captcha) != strtolower($_SESSION['captcha_val']))
            die('captcha');

        $mail->FromName = $_POST['email_fullname'];

        $mail->Subject = $_POST['email_title'];

        $mail->WordWrap = 50;

        $mail->MsgHTML($body);
   
        $mail->AddAddress($_POST['email_to']);
        $mail->AddReplyTo($_POST['email_from'], $_POST['email_fullname']);

        $mail->IsHTML(true); // send as HTML
        if (!$mail->Send()) {
            echo "Mailer Error: " . $mail->ErrorInfo;
        } else {
            die('1');
        }
        break;
    case 'goodnews':
        $cookie_life = time() + 31536000; //1 year
        $id = intval($_POST['id']);
        if (isset($_COOKIE['goodnews'])) {
            $arrVote = explode('-', $_COOKIE['goodnews']);
            if (in_array($id, $arrVote)) {
                echo 'voted';
            } else {
                $strId = $_COOKIE['goodnews'] . '-' . $id;
                setcookie('goodnews', $strId, $cookie_life);
                $sql = "UPDATE article SET thumb_up=thumb_up+1 WHERE id=$id";
                $db->query($sql);
                echo $id;
            }
        } else {
            setcookie('goodnews', $id, $cookie_life);
            $sql = "UPDATE article SET thumb_up=thumb_up+1 WHERE id=$id";
            $db->query($sql);
            echo $id;
        }
        break;
     case 'register_company':
        $cat_id         = intval($_POST['cat_id']);
        $phone          = intval($_POST['phone']);
        $fax            = intval($_POST['fax']);
        $setup          = intval($_POST['setup']);
        $address        = $_POST['address'];
        $city_id        = intval($_POST['city_id']);
        $web            = $_POST['web'];
        if($web=='Website'){
            $web = '';
        }
        $fullname       = mysql_escape_string(trim($_POST['fullname']));
        $email          = mysql_escape_string(trim($_POST['email']));
        if($email=='Email'){
            $email = '';
        }
        $verify         = strtolower(trim($_POST['verify']));
        $about          = str_replace('\n', '<br/>', (mysql_real_escape_string(trim($_POST['about']))));
        if ($verify != strtolower($_SESSION['captcha_val'])) {
            echo 'captcha_error';
        } else {
                $addCompanySql = "INSERT INTO company (name,name_link,phone,fax,email,web,address,city_id,setup,about,cat_id,active)
                                    VALUES('".$fullname."','".CleanFileName($fullname)."','".$phone."','".$fax."','".$email."','".$web."','".$address."','".$city_id."','".$setup."','".$about."','".$cat_id."','no')";
                $db_ancu->query($addCompanySql);
                echo $db_ancu->mysql_insert_id();
         }
        break;

}
?>
